<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh, Edit, Delete, Coin, Star, Setting } from '@element-plus/icons-vue'
import request from '@/utils/request'

const API_BASE_URL = (import.meta as any)?.env?.VITE_API_BASE_URL || ''

interface PointPackage {
  id: string
  name: string
  description?: string
  pointsAmount: string
  priceDecimal: string
  imageUrl?: string
  badge?: string
  sortOrder: number
  isActive: boolean
  isRecommended: boolean
  createdAt: string
  updatedAt: string
}

const packageList = ref<PointPackage[]>([])
const packageForm = reactive({
  name: '',
  description: '',
  pointsAmount: 0,
  priceDecimal: 0,
  imageUrl: '',
  badge: '',
  sortOrder: 0,
  isActive: true,
  isRecommended: false
})
const packageDialog = ref(false)
const editingId = ref<string | null>(null)
const loading = ref(false)

async function fetchPackages() {
  loading.value = true
  try {
    const { data } = await request.get('/api/admin/point-packages')
    packageList.value = data
  } catch (error) {
    ElMessage.error('포인트 상품 패키지 목록 가져오기 실패')
  } finally {
    loading.value = false
  }
}

function resetForm() {
  packageForm.name = ''
  packageForm.description = ''
  packageForm.pointsAmount = 0
  packageForm.priceDecimal = 0
  packageForm.imageUrl = ''
  packageForm.badge = ''
  packageForm.sortOrder = 0
  packageForm.isActive = true
  packageForm.isRecommended = false
  editingId.value = null
}

function openCreateDialog() {
  resetForm()
  packageDialog.value = true
}

function openEditDialog(row: PointPackage) {
  packageForm.name = row.name
  packageForm.description = row.description || ''
  packageForm.pointsAmount = Number(row.pointsAmount)
  packageForm.priceDecimal = Number(row.priceDecimal)
  packageForm.imageUrl = row.imageUrl || ''
  packageForm.badge = row.badge || ''
  packageForm.sortOrder = row.sortOrder
  packageForm.isActive = row.isActive
  packageForm.isRecommended = row.isRecommended
  editingId.value = row.id
  packageDialog.value = true
}

async function savePackage() {
  if (!packageForm.name || !packageForm.pointsAmount || !packageForm.priceDecimal) {
    ElMessage.error('이름, 포인트 수량, 가격을 입력하세요')
    return
  }

  try {
    if (editingId.value) {
      // 편집
      await request.put(`/api/admin/point-packages/${editingId.value}`, packageForm)
      ElMessage.success('업데이트 성공')
    } else {
      // 신규 추가
      await request.post('/api/admin/point-packages', packageForm)
      ElMessage.success('생성 성공')
    }
    packageDialog.value = false
    await fetchPackages()
  } catch (error) {
    ElMessage.error(editingId.value ? '업데이트 실패' : '생성 실패')
  }
}

async function togglePackage(row: PointPackage) {
  try {
    await request.put(`/api/admin/point-packages/${row.id}`, { isActive: !row.isActive })
    ElMessage.success('상태 업데이트 성공')
    await fetchPackages()
  } catch (error) {
    ElMessage.error('상태 업데이트 실패')
  }
}

async function toggleRecommended(row: PointPackage) {
  try {
    await request.put(`/api/admin/point-packages/${row.id}`, { isRecommended: !row.isRecommended })
    ElMessage.success('추천 상태 업데이트 성공')
    await fetchPackages()
  } catch (error) {
    ElMessage.error('추천 상태 업데이트 실패')
  }
}

async function deletePackage(row: PointPackage) {
  try {
    await ElMessageBox.confirm('이 포인트 상품 패키지를 삭제하시겠습니까?', '삭제 확인', {
      confirmButtonText: '확인',
      cancelButtonText: '취소',
      type: 'warning',
    })

    await request.delete(`/api/admin/point-packages/${row.id}`)
    ElMessage.success('삭제 성공')
    await fetchPackages()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('삭제 실패')
    }
  }
}

function formatPoints(points: string) {
  return Number(points).toLocaleString()
}

function formatPrice(price: string) {
  return Number(price).toLocaleString('zh-CN', { minimumFractionDigits: 2 })
}

// 이미지 업로드 성공 처리
function handleImageSuccess(res: any) {
  if (res?.coverUrl) {
    packageForm.imageUrl = res.coverUrl
  }
}

// 이미지 URL 가져오기 (상대 경로와 절대 경로 처리)
function getImageUrl(url: string) {
  if (!url) return ''
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url
  }
  return `${API_BASE_URL}${url}`
}

// 배지 옵션
const badgeOptions = [
  { label: '동메달', value: '동메달' },
  { label: '은메달', value: '은메달' },
  { label: '금메달', value: '금메달' },
  { label: '다이아몬드', value: '다이아몬드' },
  { label: '플래티넘', value: '플래티넘' }
]

// 정렬된 패키지 목록
const sortedPackages = computed(() => {
  return [...packageList.value].sort((a, b) => a.sortOrder - b.sortOrder)
})

onMounted(() => {
  fetchPackages()
})
</script>

<template>
  <div class="package-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-content">
        <el-icon class="page-icon" size="24">
          <Coin />
        </el-icon>
        <div class="header-text">
          <h1 class="page-title">포인트 상품 관리</h1>
          <p class="page-subtitle">포인트 패키지를 관리합니다</p>
        </div>
      </div>
    </div>

    <!-- 工具栏 -->
    <div class="toolbar">
      <el-button type="primary" :icon="Plus" @click="openCreateDialog" size="small">
        상품 추가
      </el-button>
      <el-button :icon="Refresh" @click="fetchPackages" size="small">
        새로고침
      </el-button>
    </div>

    <!-- 包装列表 -->
    <div v-loading="loading" class="package-list">
      <div v-if="sortedPackages.length === 0" class="empty-state">
        <el-empty description="등록된 포인트 상품이 없습니다" />
      </div>
      <div v-else class="package-cards">
        <div v-for="pkg in sortedPackages" :key="pkg.id" class="package-card">
          <div class="card-header">
            <div class="card-title-section">
              <div class="card-title">{{ pkg.name }}</div>
              <div class="card-badges">
                <el-tag v-if="pkg.badge" size="small" type="warning">{{ pkg.badge }}</el-tag>
                <el-tag v-if="pkg.isRecommended" size="small" type="danger">
                  <el-icon><Star /></el-icon>
                  추천
                </el-tag>
                <el-tag :type="pkg.isActive ? 'success' : 'info'" size="small">
                  {{ pkg.isActive ? '활성' : '비활성' }}
                </el-tag>
              </div>
            </div>
            <div class="card-actions">
              <el-button
                type="primary"
                :icon="Edit"
                @click="openEditDialog(pkg)"
                size="small"
                text
              />
              <el-button
                type="danger"
                :icon="Delete"
                @click="deletePackage(pkg)"
                size="small"
                text
              />
            </div>
          </div>

          <div class="card-content">
            <div class="package-image">
              <img
                v-if="pkg.imageUrl"
                :src="getImageUrl(pkg.imageUrl)"
                alt="상품 이미지"
                class="product-image"
              />
              <div v-else class="no-image">
                <el-icon size="32"><Coin /></el-icon>
                <span>이미지 없음</span>
              </div>
            </div>

            <div class="package-info">
              <div class="info-row">
                <span class="label">포인트:</span>
                <span class="value points">{{ formatPoints(pkg.pointsAmount) }}</span>
              </div>
              <div class="info-row">
                <span class="label">가격:</span>
                <span class="value price">¥{{ formatPrice(pkg.priceDecimal) }}</span>
              </div>
              <div class="info-row">
                <span class="label">순서:</span>
                <span class="value">{{ pkg.sortOrder }}</span>
              </div>
              <div v-if="pkg.description" class="info-row description">
                <span class="label">설명:</span>
                <span class="value">{{ pkg.description }}</span>
              </div>
            </div>
          </div>

          <div class="card-footer">
            <el-button
              :type="pkg.isActive ? 'warning' : 'success'"
              @click="togglePackage(pkg)"
              size="small"
            >
              {{ pkg.isActive ? '비활성화' : '활성화' }}
            </el-button>
            <el-button
              :type="pkg.isRecommended ? 'info' : 'danger'"
              @click="toggleRecommended(pkg)"
              size="small"
            >
              {{ pkg.isRecommended ? '추천 취소' : '추천' }}
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="packageDialog"
      :title="editingId ? '포인트 상품 패키지 편집' : '포인트 상품 패키지 추가'"
      width="90%"
      class="mobile-dialog"
    >
      <el-form :model="packageForm" label-position="top" class="mobile-form">
        <el-form-item label="상품 패키지명" required>
          <el-input v-model="packageForm.name" placeholder="예: 100,000 ALL + 동메달" />
        </el-form-item>

        <el-form-item label="상품 패키지 설명">
          <el-input
            v-model="packageForm.description"
            type="textarea"
            :rows="3"
            placeholder="상품 패키지의 상세 설명"
          />
        </el-form-item>

        <el-form-item label="포인트 수량" required>
          <el-input-number
            v-model="packageForm.pointsAmount"
            :min="1"
            class="full-width"
            controls-position="right"
          />
        </el-form-item>

        <el-form-item label="가격" required>
          <el-input-number
            v-model="packageForm.priceDecimal"
            :min="0"
            :step="0.01"
            :precision="2"
            class="full-width"
            controls-position="right"
          />
        </el-form-item>

        <el-form-item label="상품 이미지">
          <div class="image-upload-section">
            <div class="image-preview">
              <img
                v-if="packageForm.imageUrl"
                :src="getImageUrl(packageForm.imageUrl)"
                alt="상품 이미지"
                class="preview-image"
              />
              <div v-else class="no-preview">
                <el-icon size="32"><Coin /></el-icon>
                <span>이미지 없음</span>
              </div>
            </div>
            <div class="image-controls">
              <el-upload
                :action="`${API_BASE_URL}/api/admin/uploads/cover`"
                name="cover-upload"
                :with-credentials="true"
                :show-file-list="false"
                :on-success="handleImageSuccess"
                class="upload-button"
              >
                <el-button type="primary" size="small">이미지 업로드</el-button>
              </el-upload>
              <el-input
                v-model="packageForm.imageUrl"
                placeholder="또는 이미지 URL 직접 입력"
                size="small"
              />
            </div>
          </div>
        </el-form-item>

        <el-form-item label="배지 표시">
          <el-select v-model="packageForm.badge" placeholder="배지 선택" clearable class="full-width">
            <el-option
              v-for="badge in badgeOptions"
              :key="badge.value"
              :label="badge.label"
              :value="badge.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="정렬 순서">
          <el-input-number
            v-model="packageForm.sortOrder"
            :min="0"
            class="full-width"
            controls-position="right"
          />
          <div class="form-help">숫자가 작을수록 앞에 표시됩니다</div>
        </el-form-item>

        <el-form-item label="설정">
          <div class="switch-group">
            <div class="switch-item">
              <el-switch v-model="packageForm.isActive" />
              <span class="switch-label">활성화 여부</span>
            </div>
            <div class="switch-item">
              <el-switch v-model="packageForm.isRecommended" />
              <span class="switch-label">추천 여부</span>
            </div>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="packageDialog = false">취소</el-button>
          <el-button type="primary" @click="savePackage">저장</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.package-management {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 16px;
  background-color: #f5f5f5;
}

/* 页面标题 */
.page-header {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.page-icon {
  color: var(--el-color-primary);
}

.header-text {
  flex: 1;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin: 0 0 4px 0;
}

.page-subtitle {
  font-size: 14px;
  color: var(--el-text-color-regular);
  margin: 0;
}

/* 工具栏 */
.toolbar {
  display: flex;
  gap: 8px;
  margin-bottom: 16px;
}

.toolbar .el-button {
  flex: 1;
}

/* 包装列表 */
.package-list {
  flex: 1;
  overflow-y: auto;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
  background: white;
  border-radius: 8px;
}

.package-cards {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

/* 包装卡片 */
.package-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 16px;
  background: #fafafa;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.card-title-section {
  flex: 1;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin-bottom: 8px;
}

.card-badges {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
}

.card-actions {
  display: flex;
  gap: 4px;
}

.card-content {
  display: flex;
  padding: 16px;
  gap: 16px;
}

.package-image {
  flex-shrink: 0;
  width: 80px;
  height: 80px;
}

.product-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 6px;
}

.no-image {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  border-radius: 6px;
  color: var(--el-text-color-placeholder);
  font-size: 12px;
}

.package-info {
  flex: 1;
}

.info-row {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8px;
}

.info-row:last-child {
  margin-bottom: 0;
}

.info-row .label {
  font-size: 14px;
  color: var(--el-text-color-regular);
  min-width: 60px;
}

.info-row .value {
  font-size: 14px;
  color: var(--el-text-color-primary);
  text-align: right;
  flex: 1;
}

.info-row .value.points {
  font-weight: 600;
  color: var(--el-color-primary);
}

.info-row .value.price {
  font-weight: 600;
  color: var(--el-color-success);
}

.info-row.description {
  flex-direction: column;
  align-items: flex-start;
}

.info-row.description .value {
  text-align: left;
  margin-top: 4px;
  font-size: 13px;
  line-height: 1.4;
}

.card-footer {
  display: flex;
  gap: 8px;
  padding: 12px 16px;
  background: #fafafa;
  border-top: 1px solid var(--el-border-color-lighter);
}

.card-footer .el-button {
  flex: 1;
}

/* 对话框样式 */
.mobile-dialog {
  margin: 5vh auto;
}

.mobile-dialog :deep(.el-dialog) {
  border-radius: 8px;
}

.mobile-dialog :deep(.el-dialog__header) {
  padding: 16px 20px 12px;
}

.mobile-dialog :deep(.el-dialog__body) {
  padding: 0 20px 16px;
  max-height: 70vh;
  overflow-y: auto;
}

.mobile-form {
  padding: 0;
}

.mobile-form .el-form-item {
  margin-bottom: 20px;
}

.mobile-form :deep(.el-form-item__label) {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 8px;
}

.full-width {
  width: 100%;
}

.form-help {
  font-size: 12px;
  color: var(--el-text-color-regular);
  margin-top: 4px;
}

/* 图片上传区域 */
.image-upload-section {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.image-preview {
  align-self: center;
  width: 120px;
  height: 120px;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 6px;
  border: 1px solid var(--el-border-color-light);
}

.no-preview {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  color: var(--el-text-color-placeholder);
  font-size: 12px;
}

.image-controls {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.upload-button {
  align-self: center;
}

/* 开关组 */
.switch-group {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.switch-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.switch-label {
  font-size: 14px;
  color: var(--el-text-color-primary);
}

.dialog-footer {
  display: flex;
  gap: 12px;
}

.dialog-footer .el-button {
  flex: 1;
}

/* 响应式适配 */
@media (max-width: 480px) {
  .package-management {
    padding: 12px;
  }

  .header-content {
    padding: 12px;
  }

  .page-title {
    font-size: 16px;
  }

  .card-content {
    padding: 12px;
    gap: 12px;
  }

  .package-image {
    width: 60px;
    height: 60px;
  }

  .mobile-dialog {
    width: 95% !important;
    margin: 2vh auto;
  }

  .image-preview {
    width: 100px;
    height: 100px;
  }
}
</style>
